package com.ztatic.fightmode.views;

import com.ztatic.fightmode.control.ScreenHandler;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Handler;
import android.os.Looper;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class Screen extends SurfaceView implements SurfaceHolder.Callback{

	protected boolean _isRunning = false;
	private ScreenThread _thread;
	
	public Screen(Context context) {
		super(context);
		
		getHolder().addCallback(this);
		_thread = new ScreenThread(getHolder());
	}
	
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		
	}

	public void surfaceCreated(SurfaceHolder holder) {
		_isRunning = true;
		//ScreenHandler.g_Handler.registerUiThread(_thread);
		_thread.start();
	}

	public void surfaceDestroyed(SurfaceHolder holder) {
		boolean retry = true;
		_isRunning = false;
		while(retry)
		{
			try
			{
				_thread.join();
				retry = false;
			} catch (InterruptedException e) 
			{ }
		}	
	}
	
	public void onUpdate(){}
	
	@Override
	public void onDraw(Canvas c)
	{
		c.drawColor(Color.MAGENTA);
	}

	class ScreenThread extends Thread implements Runnable
	{	
		private SurfaceHolder _surfaceHolder;
		Handler handler;
		
		public ScreenThread(SurfaceHolder sh)
		{
			_surfaceHolder = sh;
		}
		
		@Override
		public void run()
		{
			while(_isRunning)
			{
				//return;
			
				Canvas c = null;
				try
				{
					c = _surfaceHolder.lockCanvas(null);
					//synchronized (_surfaceHolder)
					{
						onDraw(c);
					}
				} 
				finally
				{
					if(c != null)
					{
						_surfaceHolder.unlockCanvasAndPost(c);
					}
				}
				
				
				try {
					sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				//update the screen
				onUpdate();
			}
		};		
	}
}
